package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.db.Admin;
import com.tanhua.model.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public Map login(String username, String password, String verificationCode, String uuid) {
        password = SecureUtil.md5(password);
        String code = redisTemplate.opsForValue().get(Constants.CAP_CODE + uuid);
        if (StringUtils.isEmpty(code) || !code.equals(verificationCode)) {
            throw new BusinessException("验证码错误!");
        }
        QueryWrapper qw = new QueryWrapper();
        qw.eq("username", username);
        Admin admin = adminMapper.selectOne(qw);
        if (admin == null || !admin.getPassword().equals(password)) {
            throw new BusinessException("用户名或密码错误!");
        }

        Map map = new HashMap();
        map.put("id", admin.getId());
        map.put("username", admin.getUsername());
        String token = JwtUtils.getToken(map);
        Map map1 = new HashMap();
        map1.put("token", token);
        return map1;
    }

    public AdminVo profile() {
        Long userId = AdminHolder.getUserId();
        Admin admin = adminMapper.selectById(userId);
        AdminVo init = AdminVo.init(admin);
        return init;
    }

    public void logout() {
        AdminHolder.remove();
    }
}
